<template>
  <div class="user-container">
    <div class="user-header">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-form :inline="true" :model="form">
        <el-form-item label="请输入">
          <el-input placeholder="请输入用户名" v-model.lazy.trim="form.keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column v-for="item in tableLabel" :key="item.prop"
                         :prop="item.prop" :label="item.label" :width="item.width" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click.stop="handleDeleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="total, prev, pager, next"
                     class="pagination"
                     :total="config.total" size="small"
                     @current-change="handleCurrentChange"/>

      <el-dialog
        v-model="dialogVisible"
        :close-on-press-escape="false"
        :draggable="true"
        :close-on-click-modal="false"
        :title="action === 'add' ? '新增用户' : '编辑用户'"
        width="35%"
        :before-close="handleClose"
      >
        <!--需要注意的是设置了:inline="true"，
     会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
     在css进行处理-->
        <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formUser.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item class="select-clearn" label="性别" prop="sex">
                <el-select v-model="formUser.sex" placeholder="请选择" style="width: 100%;">
                  <el-option label="男" value="1" />
                  <el-option label="女" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birth">
                <el-date-picker
                  v-model="formUser.birth"
                  type="date"
                  placeholder="请输入"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item
              label="地址"
              prop="addr"
            >
              <el-input v-model="formUser.addr" placeholder="请输入地址" />
            </el-form-item>
          </el-row>
          <el-row style="justify-content: flex-end">
            <el-form-item>
              <el-button type="primary" @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="onSubmit">确定</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, onMounted, toRaw, nextTick} from 'vue'
import {getUserTableData, deleteUser, addUser, editUser} from '@/api/mock/api'
import {ElMessageBox, ElMessage} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const form = reactive<{keyword: string}>({keyword: ''})

const tableLabel = [
  {
    prop: 'name',
    label: '姓名'
  },
  {
    prop: 'age',
    label: '年龄'
  },
  {
    prop: 'sexLabel',
    label: '性别'
  },
  {
    prop: 'birth',
    label: '出生日期',
    width: 200
  },
  {
    prop: 'addr',
    label: '地址',
    width: 400
  }
]

const tableData = ref<any[]>([])

const config = reactive({
  name: '',
  total: 0
})

const _getUserTableData = () => {
  getUserTableData(config).then(res => {
    tableData.value = res.data?.list?.map(v => ({
      ...v,
      sexLabel: (v.sex === '1' || v.sex === 1) ? '男' : '女'
    }))
    config.total = res.data?.count || 0
  })
}

const handleSearch = () => {
  config.name = form.keyword
  _getUserTableData()
}

const handleCurrentChange = (v: number) => {
  config.page = v
  _getUserTableData()
}

const handleDeleteUser = (user) => {
  ElMessageBox.confirm('是否确定删除呢？').then( async () => {
    await deleteUser({id: user.id})
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success'
    })
    _getUserTableData()
  }).catch(() => {})
}

const action = ref<string>('add')
const dialogVisible = ref<boolean>(false)

interface RuleForm {
  name: string
  age?: number
  sex: string
  birth: string
  addr: string
}
const formUser = ref<RuleForm>({
  name: '',
  sex: '1',
  birth: '',
  addr: ''
})
//表单校验规则
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    { type: 'number', message: '年龄必须是数字' },
  ],
  sex: [{ required: true, message: '性别是必选项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必选项' }],
  addr:[{ required: true, message: '地址是必填项' }]
})

//这个方法之前定义过
const handleAdd = () => {
  action.value='add'
  //打开对话窗
  dialogVisible.value=true
}

const userForm = ref<FormInstance>()

//对话框右上角的关闭事件
const handleClose = () => {
  //获取到表单dom，执行resetFields重置表单
  userForm.value?.resetFields()
  //关闭对话框
  dialogVisible.value=false
}

//对话框右下角的取消事件
const handleCancel = () => {
  handleClose()
}

const onSubmit = () => {
  userForm.value?.validate(async (isValid) => {
    if (isValid){
      if (action.value === 'add'){
        await addUser(toRaw(formUser.value))
      } else {
        await editUser(toRaw(formUser.value))
      }
      const msg = action.value === 'add' ? '用户添加成功！' : '用户编辑成功！'
      handleClose()
      ElMessage.success(msg)
      _getUserTableData()
    } else {
      ElMessage.error('请输入正确的内容！')
    }
  })
}

const handleEdit = user => {
  action.value = 'edit'
  dialogVisible.value = true
  nextTick(() => {
    Object.assign(formUser.value, {...user, sex: '' + user.sex})
  })
}

onMounted(() => {
  _getUserTableData()
})

</script>

<style lang="less" scoped>
.user-container{
  .user-header{
    display: flex;
    justify-content: space-between;
  }
  .table-container{
    position: relative;
    height: 520px;
    .el-table{
      width: 100%;
      height: 500px;
    }
    .pagination{
      position: absolute;
      right: 10px;
      bottom: 30px;
    }
    .select-clearn{
      display: flex;
    }
  }
}
</style>